package com.wcbdota.ui;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wcbdota.R;
import com.wcbdota.base.BaseMessage;
import com.wcbdota.base.BaseUi;
import com.wcbdota.base.C;
import com.wcbdota.base.Messages;
import com.wcbdota.list.HeroGridAdapterList;
import com.wcbdota.model.Hero;
import com.wcbdota.util.AppUtil;
import com.wcbdota.util.SDUtil;
import com.wcbdota.util.UIUtil;
@SuppressWarnings("unchecked")
public class UiHero extends BaseUi {
	
	private static String TAG = UiHero.class.getSimpleName();
	private EditText ev_searchtext;
	private GridView gv_heroinfo;
	private TextView pt_tv_titlename;
	private Button bt_power;
	private Button bt_agile;
	private Button bt_wisdom;
	
	private String[] positions = {"核心","控制","对线辅助","先手","打野","辅助","耐久","爆发","推进","逃生"};
	private ArrayList<Hero> heroObjList = new ArrayList<Hero>();
	private ArrayList<Hero> heroObjListByAttribute = new ArrayList<Hero>();
	private ArrayList<Hero> heroObjListByPosition = new ArrayList<Hero>();
	private int heroPosition = 0;
	private Button[] positionbuttonarray = new Button[positions.length];;
	private LinearLayout itemlayout;
	private int currentAttribute = 1; //0:全部， 1:力量，2:敏捷，3:智力

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(0);
		if(InitScream()==true){
			System.out.println(InitScream()+"");
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 
		}
		UIUtil.updateFullscreenStatus(this, false);
		setContentView(R.layout.hero_main);
		init();
		
		if(Messages.msg.msg_UiHero == null){
			this.doTaskAsync(C.task.heroList, C.api.heroList);
		} else{
			datainit();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		try {
			heroObjList = (ArrayList<Hero>) Messages.msg.msg_UiHero.getResultList("Hero");
		} catch (Exception e) {
			Log.w(TAG, "cache Msg error");
		}
	}
	
	@Override
	public void setTheme(int resid) {
		super.setTheme(android.R.style.Theme_Black_NoTitleBar);
	}

	// //////////////////////////////////////////////////////////////////////////////////////////////
	// async task callback methods

	@Override
	public void onTaskComplete(int taskId, BaseMessage message) {
		super.onTaskComplete(taskId, message);

		switch (taskId) {
		case C.task.heroList:
				//将msg对象保存至全局存储
				Messages.msg.msg_UiHero = message;
				datainit();
			break;
		}
	}

	@Override
	public void onNetworkError(int taskId) {
		super.onNetworkError(taskId);
	}

	// //////////////////////////////////////////////////////////////////////////////////////////////
	// other methods

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}
	
	public void datainit(){
		try {
			heroObjList = (ArrayList<Hero>) Messages.msg.msg_UiHero.getResultList("Hero");
			heroObjListByAttribute = heroObjList;
			heroObjListByPosition = heroObjList;
			gv_heroinfo = (GridView) this.findViewById(R.id.gv_heroinfo);
			gv_heroinfo.setAdapter(new HeroGridAdapterList(this, heroObjListByPosition, gv_heroinfo));
			gv_heroinfo.setOnItemClickListener(gv_heroinfo_setOnItemClickListener);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void init(){
		bt_power = (Button) findViewById(R.id.bt_power);
		bt_power.setOnClickListener(mOnClickListener);
		
		bt_agile = (Button) findViewById(R.id.bt_agile);
		bt_agile.setOnClickListener(mOnClickListener);
		
		bt_wisdom = (Button) findViewById(R.id.bt_wisdom);
		bt_wisdom.setOnClickListener(mOnClickListener);
		
		findViewById(R.id.pt_bt_back).setOnClickListener(mOnClickListener);
		findViewById(R.id.pt_bt_reload).setOnClickListener(mOnClickListener);
		itemlayout = (LinearLayout) findViewById(R.id.hm_LinearLayout_positionitem);
		pt_tv_titlename = (TextView) findViewById(R.id.pt_tv_titlename);
		pt_tv_titlename.setText("英雄");
		for(int i = 0; i < positions.length; i++){
			CreatePositionItem(i);
		}
	}
	
	public void setHeroByAttribute(String Attribute){
		heroObjListByAttribute = new ArrayList<Hero>();
		for (int i = 0; i < heroObjList.size(); i++) {
			if(heroObjList.get(i).getAttribute().equals(Attribute)){
				heroObjListByAttribute.add(heroObjList.get(i));
			}
		}
		heroObjListByPosition = heroObjListByAttribute;
		gv_heroinfo.setAdapter(new HeroGridAdapterList(this, heroObjListByPosition,gv_heroinfo));
	}
	
	public void CreatePositionItem(int num){
		positionbuttonarray[num] = new Button(app);
		positionbuttonarray[num].setId(2001+num);
		positionbuttonarray[num].setText(positions[num]);
		positionbuttonarray[num].setTextSize(1, 20);
		HashMap<String, Object> hashmap = new HashMap<String, Object>();
		hashmap.put("index", num);
		positionbuttonarray[num].setTag(hashmap);
		positionbuttonarray[num].setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				HashMap<String, Object> hashmap = new HashMap<String, Object>();
				hashmap = (HashMap<String, Object>) v.getTag();
				Log.i("位置", hashmap.get("index").toString());
				int PositionNum = (Integer) hashmap.get("index") + 1;
				heroObjListByPosition = new ArrayList<Hero>();
				for(int i = 0; i < heroObjListByAttribute.size(); i++){
					String[] HeroPosition = heroObjListByAttribute.get(i).getPosition().split(",");
					
					for(int j = 0; j < HeroPosition.length; j++){
						if(Integer.valueOf(HeroPosition[j]) == PositionNum){
							heroObjListByPosition.add(heroObjListByAttribute.get(i));
							break;
						}
					}
				}
				gv_heroinfo.setAdapter(new HeroGridAdapterList(UiHero.this, heroObjListByPosition,gv_heroinfo));
			}
		});
		LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);  

		itemlayout.addView(positionbuttonarray[num],p);   //将按钮放入layout组件
	}
	
	// //////////////////////////////////////////////////////////////////////////////////////////////
	// Listener
	
	OnClickListener mOnClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.pt_bt_back:
				finish();
				break;
			case R.id.pt_bt_reload:
				UiHero.this.doTaskAsync(C.task.heroList, C.api.heroList);
				break;
			case R.id.bt_power:
				currentAttribute = 1;
				bt_power.setBackgroundResource(R.drawable.bt_power_select);
				bt_agile.setBackgroundResource(R.drawable.bt_agile);
				bt_wisdom.setBackgroundResource(R.drawable.bt_wisdom);
				setHeroByAttribute("1");
			break;
			case R.id.bt_agile:
				currentAttribute = 2;
				bt_power.setBackgroundResource(R.drawable.bt_power);
				bt_agile.setBackgroundResource(R.drawable.bt_agile_select);
				bt_wisdom.setBackgroundResource(R.drawable.bt_wisdom);
				setHeroByAttribute("2");
			break;
			case R.id.bt_wisdom:
				currentAttribute = 3;
				bt_power.setBackgroundResource(R.drawable.bt_power);
				bt_agile.setBackgroundResource(R.drawable.bt_agile);
				bt_wisdom.setBackgroundResource(R.drawable.bt_wisdom_select);
				setHeroByAttribute("3");
			break;
			}
		}
	};
	
	OnItemClickListener gv_heroinfo_setOnItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			heroPosition = position;
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.layout.hero_hreo_dialog,(ViewGroup) findViewById(R.id.hhd_dialog));
			
			TextView hhd_tv_name = (TextView) layout.findViewById(R.id.hhd_tv_name);
			hhd_tv_name.setText(heroObjListByPosition.get(position).getEnglishName());
			
			ImageView hhd_iv_herovert = (ImageView) layout.findViewById(R.id.hhd_iv_herovert);
			//String imageUrl = C.api.resbase + "/" + heroObjListTemp.get(position).getAvatar() + ".png";
			String imageUrl = C.remoteres.base + C.remoteres.heroes + "/" + heroObjListByPosition.get(position).getAvatar() + ".png";
			String cacheKey = AppUtil.md5(imageUrl);
			Bitmap bitmap = SDUtil.getImage(cacheKey);
			hhd_iv_herovert.setImageBitmap(bitmap);
			
			TextView hhd_tv_heroposition = (TextView) layout.findViewById(R.id.hhd_tv_heroposition);
			String[] positionArray = heroObjListByPosition.get(position).getPosition().split(",");
			String pos = "";
			for(int i = 0; i < positionArray.length; i++){
				pos += positions[Integer.valueOf(positionArray[i]) - 1];
				if(i!=positionArray.length - 1){
					pos += "->";
				}
			}
			
			hhd_tv_heroposition.setText(pos);
			
			new AlertDialog.Builder(UiHero.this).setTitle(heroObjListByPosition.get(position).getHeroName()).setView(layout)
			.setPositiveButton("查看详细", new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog,
						int which) {
					Intent i = new Intent(UiHero.this, UiHeroDetail.class);
					Hero hero = heroObjListByPosition.get(heroPosition);
					i.putExtra("hero", hero);
					startActivity(i);
				}
				
			})
			.setNegativeButton("返回", null).show();
		}
	};
}